//
//  ViewController.m
//  DemoCoreData
//
//  Created by tangkexiong on 16/3/14.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "ViewController.h"

#import "YCCoreDataManager+CDProduct.h"
#import "YCCoreDataManager+CDProductCategory.h"

#import "ProductEditViewController.h"

#import "CDProductCategory.h"
#import "CDProduct.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, ProductEditVCDelegate, NSFetchedResultsControllerDelegate> {
    NSFetchedResultsController *_fetchedResultsController;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self initFetchedResultsController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initFetchedResultsController {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CDProduct"];
    NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"mCategory.mName" ascending:YES];
    [request setSortDescriptors:@[nameSort]];
    
    NSManagedObjectContext *moc = [YCCoreDataManager sharedInstance].managedObjectContext;
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:moc sectionNameKeyPath:@"mCategory.mName" cacheName:nil];
    _fetchedResultsController.delegate = self;
    NSError *error = nil;
    
    if (![_fetchedResultsController performFetch:&error]) {
        NSLog(@"error, %@", [error localizedDescription]);
        abort();
    }
    
}

#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [[self tableView] insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeMove:
        case NSFetchedResultsChangeUpdate:
            break;
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [[self tableView] insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeDelete:
            [[self tableView] deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
        case NSFetchedResultsChangeUpdate:
            [self configureCell:[[self tableView] cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;
        case NSFetchedResultsChangeMove:
            [[self tableView] deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [[self tableView] insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [[self tableView] endUpdates];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[_fetchedResultsController sections] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id<NSFetchedResultsSectionInfo> sectionInfo = [_fetchedResultsController sections][section];
    return sectionInfo.name;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[_fetchedResultsController sections][section] numberOfObjects];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    [self configureCell:cell atIndexPath:indexPath];
    
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath*)indexPath
{
    CDProductCategory *category = [_fetchedResultsController objectAtIndexPath:indexPath];
    CDProduct *product = category.mProducts[indexPath.row];
    // Populate cell from the NSManagedObject instance
    cell.textLabel.text = product.mName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.02lf", [product.mPrice doubleValue]];;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductEditViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"vcProductEdit"];
    
//    vc.product = _categoryArray[indexPath.section].mProducts[indexPath.row];
//    vc.myDelegate = self;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        [self.refreshControl beginRefreshing];
//        
//        YCProductCategory *category = _categoryArray[indexPath.section];
//        
//        [[YCCoreDataManager sharedInstance] deleteProduct:category.mProducts[indexPath.row] block:^(NSError *error) {
//            if (error == nil) {
//                NSMutableArray *array = [NSMutableArray arrayWithArray:category.mProducts];
//                [array removeObject:category.mProducts[indexPath.row]];
//                category.mProducts = array;
//                [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//            }
//            
//            [self.refreshControl endRefreshing];
//        }];
//    }
}

#pragma mark - ProductEditVCDelegate

- (void)productEditVC:(ProductEditViewController *)vc didEdit:(YCProduct *)product isAdd:(BOOL)isAdd {
    [self.navigationController popToViewController:self animated:YES];
}

#pragma mark - IBAction

- (IBAction)addBtnClicked:(id)sender {
    ProductEditViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"vcProductEdit"];
    
    vc.myDelegate = self;
    
    [self.navigationController pushViewController:vc animated:YES];
}

@end
